package com.logistics.route.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.logistics.organization.entity.domain.Organization;
import com.logistics.organization.entity.model.OrganizationRow;
import com.logistics.role.entity.domain.Role;
import com.logistics.route.entity.domain.Route;
import com.logistics.route.entity.model.RoutePager;
import com.logistics.route.entity.model.RouteRow;
import com.logistics.route.entity.model.RouteSave;
import com.logistics.route.mapper.RouteMapper;
import com.logistics.utils.aspect.annotation.Insert;
import com.logistics.utils.aspect.annotation.Pager;
import com.logistics.utils.bean.ResultPager;
import com.logistics.utils.constants.Message;
import com.logistics.utils.exception.MessageException;
import com.logistics.utils.message.Manager;
import com.logistics.utils.tool.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RouteService extends ServiceImpl<RouteMapper, Route> {


    /**
     * 分页查询
     * @param param
     * @return
     */
    @Pager
    public ResultPager pager(RoutePager param){
        IPage page = new Page(param.getCurrent(), param.getPageSize());
        QueryWrapper<Route> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Route::getParentId, 0);
        if(StringUtils.isNotNull(param.getName())){
            queryWrapper.lambda().like(Route::getName, param.getName());
        }
        IPage<Route> result = this.page(page, queryWrapper.lambda().orderByDesc(Route::getCreateTime));
        return new ResultPager(dataFormatter(result.getRecords()), (int)result.getTotal());
    }

    /**
     * 查询所有数据平铺没有树形结构
     * @return
     */
    public List<RouteRow> listAllTile(){
        return this.list().stream().map(e -> RouteRow.build(e)).collect(Collectors.toList());

    }

    /**
     * 查找全部
     * @return
     */
    public List<RouteRow> listAll(){
        return dataFormatter(this.list(new LambdaQueryWrapper<Route>().eq(Route::getParentId, 0)));
    }

    /**
     * 根据ID查找树形
     * @param ids
     * @return
     */
    public List<RouteRow> listByIds(String ids) throws MessageException {
        if(StringUtils.isNull(ids)){
            throw new MessageException(Manager.getMessage(Message.MSG1005.getCode()));
        }
        List<RouteRow> rows = this.list(new LambdaQueryWrapper<Route>().in(Route::getId,
                StringUtils.splitToList(ids, ",").stream().distinct().collect(Collectors.toList())))
                .stream().map(e -> RouteRow.build(e)).collect(Collectors.toList());
        return rows.stream().filter(e -> e.getParentId() == 0).map(e -> {
                    e.setChildren(getChildren(e, rows));
                    return e;
                }).collect(Collectors.toList());

    }

    /**
     * 查询详细
     * @param id
     * @return
     * @throws MessageException
     */
    public RouteRow details(String id) throws MessageException {
        if(StringUtils.isNull(id)){
            throw new MessageException(Manager.getMessage(Message.MSG1005.getCode()));
        }
        return RouteRow.build(this.getOne(new LambdaQueryWrapper<Route>().eq(Route::getId, id)));
    }


    /**
     * 保存
     * @param save
     */
    @Insert
    @Transactional
    public void save(RouteSave save){
        if(StringUtils.isNull(save.getId())){
            this.save(Route.build(save));
        }else {
            this.update(Route.build(save), new LambdaQueryWrapper<Route>().eq(Route::getId, save.getId()));
        }
    }

    /**
     * 删除
     * @param ids
     * @throws MessageException
     */
    public void remove(String ids) throws MessageException {
        if(StringUtils.isNull(ids)){
            throw new MessageException(Manager.getMessage(Message.MSG1005.getCode()));
        }
        this.remove(new LambdaQueryWrapper<Route>().in(Route::getId, StringUtils.splitToList(ids, ",")));
    }


    /**
     * 获取子项
     * @param root
     * @param allList
     * @return
     */
    private List<RouteRow> getChildren(RouteRow root, List<RouteRow> allList){
        return allList.stream().filter(e -> e.getParentId() == root.getId()).map(e ->{
            e.setChildren(getChildren(e, allList));
            return e;
        }).collect(Collectors.toList());
    }

    /**
     * 数据转换
     * @param rows
     * @return
     */
    private List<RouteRow> dataFormatter(List<Route> rows){
        List<Integer> ids = rows.stream().map(e -> e.getId()).collect(Collectors.toList());
        List<Route> allList = ids.size() > 0 ? this.list(new LambdaQueryWrapper<Route>().in(Route::getParentId, ids).
                orderByDesc(Route::getCreateTime)) :
                new ArrayList<>();
        return rows.stream().map(e -> RouteRow.build(e))
                .map(e -> {
                    e.setChildren(getChildren(e, allList.stream().map(s -> RouteRow.build(s)).collect(Collectors.toList())));
                    return e;
                }).collect(Collectors.toList());
    }
}
